// pages/auto-reply-official-account/index.js
import inOrder from '../../utils/promise-inorder'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    account: [
      {appid: 'wxe078e56838ad7e75', secret: '455a796cc95baf06205d289eb83b735e', token: '', template_id: '1uCuRFC7ZKs4SXB45SMBKDLt3xwSPrcHRpGC-G7ySWs', user_list: []},
      {appid: 'wxbb3945cba54bd7c7', secret: '03ae134b3b64793d909df8551f8f0ebf', token: '', template_id: '0CN_HLJIawQcojghG9AOI5Xnh4ie0C5iP74mJYg8_jk', user_list: []},
      // {appid: 'wxa50951b8c2caaed9', secret: '455a796cc95baf06205d289eb83b735e', token:''},
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  getToken(){
    const storageAccount = wx.getStorageSync('account')
    if (storageAccount && storageAccount.filter(item => item.token == '').length == 0) return

    let promiseArr = []
    this.data.account.forEach(item => {
      promiseArr.push(() => this.getTokenApi(item)) 
    })
    inOrder(promiseArr).then(data => {
      data.map((dataItem, index) => {
        console.log(dataItem, index);
        const access_token = dataItem.data.access_token
        if (access_token) {
          this.data.account[index].token = access_token
        }
      })
      this.setData({
        account: this.data.account
      })
      wx.setStorageSync('account', this.data.account)
    })
  },

  getUserList(){
    const storageAccount = wx.getStorageSync('account')
    this.data.account = storageAccount
    let promiseArr = []
    this.data.account.forEach(item => {
      promiseArr.push(() => this.getUserListApi(item.token)) 
    })
    inOrder(promiseArr).then(data => {
      data.map((dataItem, index) => {
        console.log(dataItem, index);
        const count = dataItem.data.count
        if (count) {
          this.data.account[index].user_list = dataItem.data.data.openid
        }
      })
      this.setData({
        account: this.data.account
      })
    })
  },

  sendTemplateMessage(){
    let promiseArr = []
    this.data.account.forEach((item, index) => {
      item.user_list.forEach(userItem => {
        const accountInfo = {
          token: this.data.account[index].token,
          openid: userItem,
          template_id: this.data.account[index].template_id
        }
        // console.log(accountInfo);
        promiseArr.push(() => this.sendTemplateMessageApi(accountInfo)) 
      })
    })

    inOrder(promiseArr).then(data => {
      data.map((dataItem, index) => {
        console.log(dataItem, index);
      })
    })
  },

  // 获取token
  getTokenApi(accountInfo){
    return new Promise((resolve, reject) => {
      // https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
      const {appid, secret} = accountInfo
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/token',
        data: {
          grant_type: 'client_credential',
          appid,
          secret
        },
        success: res => {
          resolve(res);
        },
        fail: err => {
          reject(err);
        }
      })
    })
  },

  //获取用户列表
  getUserListApi(access_token){
    return new Promise((resolve, reject) => {
      // http请求方式: GET（请使用https协议）https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/user/get',
        data: {
          access_token,
        },
        success: res => {
          resolve(res);
        },
        fail: err => {
          reject(err);
        }
      })
    })
  },

  //发送文本消息
  sendTemplateMessageApi(accountInfo){
    return new Promise((resolve, reject) => {
      // http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' + accountInfo.token,
        method: 'POST',
        data: {
          "touser": accountInfo.openid,
          "template_id": accountInfo.template_id,
          "data": {
              "thing01": {
                  "value": "嘿嘿"
              },
              "amount01": {
                  "value": "￥100"
              },
              "thing02": {
                  "value": "广州至北京"
              },
              "time01": {
                  "value": "2024年9月3日 15:00"
              }
          }
        },
        success: res => {
          resolve(res);
        },
        fail: err => {
          reject(err);
        }
      })
    })
  }
})